package com.liuyucheng.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class CharsetRecovery {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String originalStr = "170433080000000229-衢州市柯城区沟溪乡人民政府.g";
        String gbk = new String(originalStr.getBytes("UTF-8"), "GBK");
        System.out.println("gbk = " + gbk);
        String utf = new String(gbk.getBytes("GBK"), "UTF-8");
        System.out.println("utf = " + utf);


//        // 乱码字符串（UTF-8被错误用GBK展示的结果）
//        String garbledString = "170433080000000229-琛㈠窞甯傛煰鍩庡尯娌熸邯涔′汉姘戞斂搴?g";
//        System.out.println("乱码字符串: " + garbledString);
//
//        // 恢复原始UTF-8字符串
//        String recoveredString = recoverFromGbkMojibake(garbledString);
//        System.out.println("恢复后字符串: " + recoveredString);
    }

    /**
     * 将UTF-8编码被错误用GBK解码导致的乱码恢复为原始字符串
     * @param garbledString 乱码字符串
     * @return 恢复后的原始字符串
     */
    public static String recoverFromGbkMojibake(String garbledString) {
        try {
            // 关键步骤：将乱码字符串按GBK编码为字节数组，再用UTF-8解码
            byte[] bytes = garbledString.getBytes(Charset.forName("GBK"));
            return new String(bytes, Charset.forName("UTF-8"));
        } catch (Exception e) {
            System.err.println("编码转换失败: " + e.getMessage());
            return garbledString; // 转换失败时返回原始乱码
        }
    }
}
